package com.atguigu.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.orders.service.OrderInfoService;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.RefundInfoService;
import com.atguigu.yygh.orders.service.WeiXinService;
import com.atguigu.yygh.orders.util.ConstantPropertiesUtils;
import com.atguigu.yygh.orders.util.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-19 14:30
 **/
@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RefundInfoService refundInfoService;

    //微信退款的实现方法
    @Override
    public Boolean refund(Long orderId) {

        // 首先获取支付订单信息
        PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId);

        // 保存支付订单信息
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        // 如果数据已经退款  我们需要进行判断
        if (refundInfo.getRefundStatus() == RefundStatusEnum.REFUND.getStatus()) {
            return true;
        }

        try {
            // 保存成功之后包装发送给微信的接口数据
            Map<String, String> paramMap = new HashMap<>(8);
            paramMap.put("appid", ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", refundInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", refundInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + refundInfo.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");

            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            // 获取返回的数据
            String xml = client.getContent();
            Map<String, String> paramMapCall = WXPayUtil.xmlToMap(xml);
            if (null != paramMapCall && WXPayConstants.SUCCESS.equalsIgnoreCase(paramMapCall.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(paramMapCall.get("refund_id"));
                refundInfo.setCallbackContent(JSONObject.toJSON(paramMapCall).toString());
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());

                // 进而更新数据
                refundInfoService.updateById(refundInfo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //根据订单号去微信第三方查询支付状态
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {

        try {
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            // 第一步需要封装数据
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 第二步需要远程调用微信接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            // 第三步需要封装接口返回的数据
            Map<String, String> map = WXPayUtil.xmlToMap(client.getContent());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //生成微信二维码  固定金额
    @Override
    public Map createNative(Integer orderId) {

        try {
            // 进行订单数据获取
            OrderInfo order = orderInfoService.getOrders(orderId);
            // 数据持久化到数据库
            paymentInfoService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            // 然后封装消息
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            Date reserveDate = order.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊" + order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//为了测试
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");
            // 利用Httpclient进行远程调用微信接口
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //封装微信接口返回的数据
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            // 返回第三方资源
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
